<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="5" :sm="12">
              <a-form-item label="姓名">
                <a-input :allowClear="true" v-model="queryParam.fullname" placeholder="请输入姓名"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="12">
              <a-form-item label="手机号">
                <a-input :allowClear="true" v-model="queryParam.mobile" placeholder="请输入手机号"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="12">
              <a-form-item label="所属角色">
                <a-select :allowClear="true" v-model="queryParam.role_id" placeholder="所属角色">
                  <a-select-option :value="item.id" v-for="item in rolesList" :key="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="12">
              <a-form-item label="状态">
                <a-select :allowClear="true" v-model="queryParam.status" placeholder="请选择状态">
                  <a-select-option :value="index" v-for="(item, index) in statusList" :key="index">{{ item.text }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="3" :sm="12">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm()">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator" v-action:add_town_admin>
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="customer_id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="action" slot-scope="text, record" v-if="record.role != 1">
          <template>
            <a @click="handleEdit(record)" v-action:give_role_to_user>角色配置</a>
            <a-divider type="vertical"/>
            <a @click="handleRemove(record)" v-action:del_town_admin>移除</a>
          </template>
        </span>
      </s-table>
      <!-- 增/查/改 弹出模板 -->
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
        :okHidden="okHidden"
        :rolesList="rolesList"
      />
      <!-- 删除/停用确认窗 -->
      <a-modal
        title="提示"
        :visible="modal.show"
        :confirm-loading="modal.loading"
        @ok="modal.confirm"
        @cancel="modal.show = false"
      >
        <p>{{ modal.text }}</p>
      </a-modal>
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { rolesList, addTownAdmin, adminList, delTownAdmin, giveRole2User } from '@/api'
import CreateForm from './modules/CreateContentForm'

const statusMap = {
  0: {
    status: 'default',
    text: '未激活'
  },
  1: {
    status: 'success',
    text: '启用'
  },
  2: {
    status: 'error',
    text: '停用'
  },
  3: {
    status: 'error',
    text: '删除'
  }
}

const columns = [
  {
    title: '姓名',
    dataIndex: 'fullname',
    align: 'center'
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    align: 'center'
  },
  {
    title: '角色',
    dataIndex: 'role_name',
    customRender: (text, record) => {
      return record.role == 1 ? '主管理员' : text
    },
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '250px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    STable,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      okHidden: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      params: {},
      isPost: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        if (!this.isPost) {
          return Promise.reject(parameter)
        }
        const params = {
          page: parameter.pageNo,
          per_page: parameter.pageSize
        }
        const res = await adminList({ ...params, ...this.queryParam })
        const result = {
          pageNo: res.current_page,
          totalPage: res.last_page,
          data: res.data,
          pageSize: 10,
          totalCount: res.total
        }
        return Promise.resolve(result)
      },
      modal: {
        show: false,
        text: '',
        loading: false,
        confirm: () => {},
        cancel: () => {}
      },
      rolesList: [],
      selectedRowKeys: [],
      selectedRows: [],
      statusList: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.params = JSON.parse(decodeURIComponent(this.$route.query['#'] || '') || '{}')
    this.$nextTick(() => {
      const s = this.$route.query['#'] || ''
      console.log('创建窗口', s)
      if (s === '') {
        this.isPost = true
        this.$refs.table.refresh()
      }
    })
    statusMap.length = 4
    this.statusList = Array.from(statusMap)
    rolesList().then(res => {
      this.rolesList = res?.list || []
      if (this.params.role_id) {
        const index = this.rolesList.findIndex(v => v.id == this.params.role_id)
        if (index > -1) {
          this.queryParam.role_id = this.params.role_id
          this.isPost = true
          this.$refs.table.refresh()
        }
      }
    })
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    async handleEdit (record) {
      this.mdl = { ...record }
      this.okHidden = true
      this.visible = true
    },
    async routeOperaDetail (record) {
      this.$router.push({
        path: '/admin/volunteer/opera-detail',
        query: { '#': encodeURIComponent(JSON.stringify(record)) }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const success = (res, info) => {
            if (res && res.is_ok == 'Y') {
              this.handleVisible()
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info(info)
            }
          }
          const final = () => { this.confirmLoading = false }
          if (this.mdl && this.mdl.customer_id > 0) {
            giveRole2User({
              customer_ids: [this.mdl.customer_id],
              role_id: values.role_id
            })
            .then(res => success(res, '配置成功'))
            .finally(final)
          } else {
            addTownAdmin(values)
              .then(res => success(res, '新增成功'))
              .finally(final)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    openModal (method, record, statusText) {
      this.modal = {
        ...this.modal,
        text: `确定${ statusText }该管理员吗？`,
        show: true,
        confirm: async () => {
          try {
            this.modal.loading = true
            const res = await method({ customer_id: record.customer_id })
            if (res.is_ok == 'Y') {
              this.modal.loading = false
              this.modal.show = false
              this.$refs.table.refresh()
              this.$message.info(`${ statusText }成功`)
            }
          } catch (err) {
            console.warn(err)
            this.modal.loading = false
          }
        }
      }
    },
    handleCancel () {
      this.handleVisible()
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    async handleRemove (record) {
      this.openModal(delTownAdmin, record, '删除')
    },
    handleVisible () {
      this.visible = false
      setTimeout(() => {
        this.okHidden = false
      }, 350)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {}
      this.$refs.table.refresh(true)
    }
  }
}
</script>
